package company.maestro;



import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;


public class SessionButtonDBAdapter 
{
  private static final String DATABASE_NAME = "maestro.db";
  public static final String DATABASE_TABLE = "sessions";
  private static final int DATABASE_VERSION = 6;
 
  public static final String KEY_ID = "_id";
  public static final String KEY_SESSION_NAME = "session_name";
  public static final String KEY_SESSION_POSITION= "session_position";
  
  private SQLiteDatabase db;
  private final Context context;
  private sessionButtonDBOpenHelper dbHelper;

  public SessionButtonDBAdapter(Context _context) 
  {
    this.context = _context;
    dbHelper = new sessionButtonDBOpenHelper(context, DATABASE_NAME, 
                                    null, DATABASE_VERSION);
   
  }
  
  public void close() 
  {
    db.close();
  }
  
  public void open() throws SQLiteException 
  {  
    try 
    {
      db = dbHelper.getWritableDatabase();
    } 
    catch (SQLiteException ex) 
    {
      db = dbHelper.getReadableDatabase();
    }
  }  
  
  /**Insert a new Seession
   * @param _sessionButton
   * @return a long value
   */
  public long insertSession(SessionButton _sessionButton) 
  {
    // Create a new row of values to insert.
    ContentValues newTaskValues = new ContentValues();
    // Assign values for each row.
    newTaskValues.put(KEY_SESSION_NAME, _sessionButton.getName());
    newTaskValues.put(KEY_SESSION_POSITION, _sessionButton.getPosition());
    // Insert the row.
    return db.insert(DATABASE_TABLE, null, newTaskValues);
  }

  /** Remove a task based on its index
   * 
   * @param _rowIndex
   * @return boolean
   */
  public boolean removeSessionButton(long _rowIndex) 
  {
    return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
  }

  // Update a task
  public boolean updateSessionButton(long _rowIndex, String _task) 
  {
    ContentValues newValue = new ContentValues();
    newValue.put(KEY_SESSION_NAME, _task);
    return db.update(DATABASE_TABLE, newValue, KEY_ID + "=" + _rowIndex, null) > 0;
  }
  
  public Cursor getAllSessionButtonsCursor() 
  {
	String orderByString = KEY_SESSION_POSITION;  
	
    return db.query(DATABASE_TABLE, 
                    new String[] { KEY_ID, KEY_SESSION_NAME, KEY_SESSION_POSITION },  
                    null, null, null, null, orderByString + " asc");
  }

  public Cursor setCursorToSessionButton(long _rowIndex) throws SQLException 
  {
    Cursor result = db.query(true, DATABASE_TABLE, 
	                           new String[] {KEY_ID, KEY_SESSION_NAME},
                             KEY_ID + "=" + _rowIndex, null, null, null, 
                             null, null);
    if ((result.getCount() == 0) || !result.moveToFirst()) 
    {
      throw new SQLException("No to do items found for row: " + _rowIndex);
    }
    return result;
  }

  public SessionButton getSessionButton(String _sessionButtonPosition[]) throws SQLException 
  {
	
    Cursor cursor = db.query(true, 
    						 DATABASE_TABLE, 
    						 new String[] {KEY_SESSION_NAME, KEY_SESSION_POSITION},
                             KEY_SESSION_POSITION + "=" + "?",
                             _sessionButtonPosition, 
                             null, 
                             null, 
                             null, 
                             null);
    
    if ((cursor.getCount() == 0) || !cursor.moveToFirst()) 
    {
      throw new SQLException("No to do item found for row: " + _sessionButtonPosition);
    }

    String sessionName = cursor.getString(cursor.getColumnIndex(KEY_SESSION_NAME));
    long position = cursor.getLong(cursor.getColumnIndex(KEY_SESSION_POSITION));
		  
    SessionButton result = new SessionButton(sessionName, position);
    return result;  
  }
  
  private static class sessionButtonDBOpenHelper extends SQLiteOpenHelper 
  {

	  public sessionButtonDBOpenHelper(Context context, String name,
	                          CursorFactory factory, int version) 
	  {
	    super(context, name, factory, version);
	  }

	  // SQL Statement to create a new database.
	  private static final String DATABASE_CREATE = "create table " + 
	    DATABASE_TABLE + " (" + 
	    KEY_ID + " integer primary key autoincrement, " +
	    KEY_SESSION_NAME + " text not null, " + 
	    KEY_SESSION_POSITION + " long);";

	  @Override
	  public void onCreate(SQLiteDatabase _db) 
	  {
	    _db.execSQL(DATABASE_CREATE);
	  }

	  @Override
	  public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
	  {
	    Log.w("ButtonDBAdapter", "Upgrading from version " + 
	                           _oldVersion + " to " +
	                           _newVersion + ", which will destroy all old data");

	    // Drop the old table.
	    _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
	    // Create a new one.
	    onCreate(_db);
	  }
	}
}